#!/bin/bash
set -x

juju-log -l INFO "Getting file fs token details."
status-set maintenance "Getting file fs token details." || true

function set_token() {
    token_name=$1           # i.e. single-fs-token
    fs_path=$2              # i.e. /srv/single-fs/ or /srv/multi-fs/multi-fs/13

    token="$(config-get $token_name)"
    token_file="$fs_path/token"

    juju-log -l INFO "Token file: $token_file"

    if [ -f $token_file ]; then
        juju-log -l INFO "Using stored token details."

        # If we have a token and we have a token file, check the contents if the differ update it otherwise use it.
        current_file_token=$(cat $token_file | grep "$token_name" | head -1 | cut -d":" -f2)
        if [ "$current_file_token" != "$token" ]; then
            token=$token
        else
            token=$(cat $token_file)
        fi
    fi

    if [[ -z $token ]]; then
        fs_token="not set"
        juju-log -l WARNING "$fs_token"
    else
        fs_token="$token"
        echo "$token" > $token_file
        juju-log -l INFO "$fs_token"
    fi

    # Return the token value.
    echo "$fs_token"
}

# Clear any previous tokens or state.
echo > /tmp/status

# First the single token
single_fs_token=$(set_token "single-fs-token" "/srv/single-fs")

juju-log -l INFO "Setting single token details."
echo "single-fs-token:$single_fs_token" >> /tmp/status

# Then the multi-fs token
for unit in $(storage-list multi-fs); do
    fs_path=$(storage-get -s $unit | grep "^location:\ " | cut -d: -f2 | tr -d ' ')
    multi_fs_token=$(set_token "multi-fs-token" "$fs_path")
    juju-log -l INFO "Setting multi token details."
    unit_token_number=$(echo $unit | cut -f2 -d"/")
    echo "multi-fs-token/$unit_token_number:$multi_fs_token" >> /tmp/status
done

status-set active "Stored token: /tmp/status" || true
